package com.exception;

import com.alibaba.fastjson.JSON;
import com.util.JsonResult;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//对控制器进行增强处理
@ControllerAdvice
public class HandlerControllerException {

    //HandlerMethod method ：代表出现异常的方法
    @ExceptionHandler(RuntimeException.class)
    public Object handlerException(RuntimeException e, HttpServletResponse response, HandlerMethod method){
        //打印异常信息，方便开发找bug
        e.printStackTrace();
        if (method.hasMethodAnnotation(ResponseBody.class)){  //说明页面需要JSON格式数据
            String errorMsg = "操作失败，请联系管理员";
            if (e instanceof LogicException){   // 说明是登录地方的异常，需要使用自定义异常信息
                errorMsg = e.getMessage();
            }
            JsonResult json = new JsonResult(false,errorMsg);
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().print(JSON.toJSONString(json));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return null;
        }else {
            return "common/error";
        }
    }

    //捕获没有权限异常
    @ExceptionHandler(UnauthorizedException.class)
    public Object handlerUnauthorized(RuntimeException e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        //方便开发的时候找bug
        e.printStackTrace();
        //判断是否有ResponseBody注解，如果是ajax对应的方法，就返回JsonResult,
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false,"您没有权限操作！")));
            return null;
        }else{
            //如果不是，就返回错误的视图页面
            return "common/nopermission";
        }
    }
}
